package com.wll.store.common.component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充
 * 通过反射获取到实体对象，然后对实体对象中的字段进行填充
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName("createTime", metaObject);
        if (null == createTime) {
            setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }

        Object createBy = getFieldValByName("createBy", metaObject);
        if (null == createTime) {
            setFieldValByName("createBy", "system", metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object modifyTime = getFieldValByName("modifyTime", metaObject);
        if (null == modifyTime) {
            setFieldValByName("modifyTime", LocalDateTime.now(), metaObject);
        }

        Object modifyBy = getFieldValByName("modifyBy", metaObject);
        if (null == modifyBy) {
            setFieldValByName("modifyBy", "system", metaObject);
        }
    }
}
